﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;

namespace digiTwitter.Core
{
    public class HTTPRequester
    {
        /// <summary>
        /// Generates a POST request to a given URL and return the results as String.
        /// </summary>
        public static XmlDocument RequestPOSTResponse(string url, string parameters)
        {
            XmlDocument doc = new XmlDocument();

            // Create the web request
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            ServicePointManager.Expect100Continue = false;

            request.PreAuthenticate = true;
            request.Credentials = GetCredentials();
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = parameters.Length;

            request.Method = "POST";
            // Write the request
            var stOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);

            if (!String.IsNullOrEmpty(parameters))
                stOut.Write(parameters);

            stOut.Close();
            try
            {
                // Get the Web Response  
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        doc.Load(reader);
                }
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse)
                    throw new TwitterException(ex.Message);
            }
            return doc;
        }

        /// <summary>
        /// Generates a GET request to a given URL and return the results as String.
        /// </summary>
        /// <param name="requestURL"></param>
        /// <returns></returns>
        public static string GetResponseString(String requestURL)
        {
            string results = "";
            try
            {
                using (var client = new WebClient())
                {
                    client.Credentials = GetCredentials();

                    using (Stream stream = client.OpenRead(requestURL))
                    {
                        using (var reader = new StreamReader(stream))
                            results = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse)
                   throw new TwitterException(ex.Message);
            }
            return results;
        }

        /// <summary>
        /// Retrieves the credentials from the Web.config keys: TwitterUsername and TwitterPassword.
        /// This is useful if you need to exceed the maximun limit of request per hour (100).
        /// You will also need to request to be withelisted: http://twitter.com/help/request_whitelisting
        /// </summary>
        /// <returns></returns>
        private static ICredentials GetCredentials()
        {

            if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["TwitterUsername"]) &&
                !String.IsNullOrEmpty(ConfigurationManager.AppSettings["TwitterPassword"]))
            {
                return new NetworkCredential(ConfigurationManager.AppSettings["TwitterUsername"],
                                             ConfigurationManager.AppSettings["TwitterPassword"]);
            }

            return CredentialCache.DefaultNetworkCredentials;
        }
    }
}
